<template>
  <div class="tag">
    <div
      class="tagcart"
      v-for="(item, i) in state.list"
      :key="i"
      :class="{ active: route.path == item.path }"
      @click="router.push(item.path)"
    >
      <span>{{ item.title }}</span>
      <span
        class="cuo"
        @click.stop="del(i)"
      >×</span>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, onMounted, watch } from "vue";
import { message } from "ant-design-vue";
import { onBeforeRouteUpdate, useRouter, useRoute } from "vue-router";
import { string } from "vue-types";
const state: any = reactive({
  list: [
    {
      path: "/dashboard",
      title: "仪表盘",
    },
  ],
  num: 0,
});
const route = useRoute();
const router = useRouter();
const addlist = (obj: any) => {
  let index = state.list.findIndex((item: any) => item.path == obj.path);
  if (index == -1) {
    state.list.push(obj);
  }
};
onMounted(() => {
  state.list = JSON.parse(sessionStorage.getItem("setmian")) || [];
  addlist({ path: route.path, title: route.meta.title });
});
onBeforeRouteUpdate((to, from, next) => {
  addlist({ path: to.path, title: to.meta.title });
  next();
});
const del = (i: number) => {
  if (state.list.length == 1) {
    message.error("无法删除");
    return false;
  }
  state.list.splice(i, 1);
  router.push(state.list.at(-1).path);
};
watch(
  () => state.list,
  (newVal, oldVal) => {
    sessionStorage.setItem("setmian", JSON.stringify(newVal));
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.tag {
  width: 100%;
  margin: 10px 2%;
  height: 40px;
  line-height: 40px;
  display: flex;
  .tagcart {
    border: 1px solid #000;
    height: 40px;
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 0 20px;
    margin-right: 5px;
    border-radius: 5px;
    background: #fff;
    .cuo {
      margin-left: 20px;
      float: right;
      width: 20px;
      height: 20px;
      text-align: center;
      line-height: 20px;
      font-size: 18px;
      border-radius: 50%;
    }
  }
  .active {
    color: black;
    background-color: skyblue;
  }
}
</style>